/**
 * 工厂模式
 */
class Product {
    constructor(args) {
        this.args = args
    }

    func() {
        console.log(this.args);
    }
}

class Factory {
    create() {
        return new Product('aaa')
    }
}

let a = new Factory()
let create = a.create()
let fn = create.func() // 'aaa'


/**
 * 单例模式
 */
class Dialog {
    constructor() {
        this.state = 'hide'
    }

    show() {
        if (this.state === 'show') {
            return alert('已经显示了')
        }
        console.log('显示');
        this.state = 'show'
    }
    hide() {
        if (this.state === 'hide') {
            alert('已经隐藏了')
            return
        }
        console.log('隐藏');
        this.state = 'hide'
    }
    static getInstance = (function () {
        let instance;
        return function () {
            if (!instance) {
                instance = new Dialog()
            }
            return instance
        }
    })()
}

let obj = Dialog.getInstance()
let obj2 = Dialog.getInstance()
obj.show()
obj === obj2 // true



/**
 * 发布订阅模式(观察者模式)
 */
class Sub {
    constructor() {
        // 用于存储发布的函数
        this.list = {}
    }
    // 订阅
    on(eventName, fn) {
        if (!(this.list[eventName])) {
            this.list[eventName] = [{ fn }]
        }
        this.list[eventName].push({ fn })
    }

    // 发布
    emit(eventName, params) {
        if (this.list[eventName]) {
            this.list[eventName].forEach(item => {
                item.fn(params)
            });
        }
    }

    // 解除事件绑定
    off(eventName) {
        if (this.list[eventName]) {
            delete this.list[eventName]
        }
    }
}